package com.yuexun.dhdoctor.module.my.ui;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.base.bean.ActValue;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.email.ui.Act_GetMailList;
import com.yuexun.dhdoctor.module.my.adapter.MessageAdapter;
import com.yuexun.dhdoctor.module.my.bean.MessageInfoBean;
import com.yuexun.dhdoctor.module.my.bean.MessageInfoBeanDate;
import com.yuexun.dhdoctor.module.my.model.impl.MessageDetailModel;
import com.yuexun.dhdoctor.module.my.model.impl.MessageModel;
import com.yuexun.dhdoctor.module.my.presenter.IMessageDetailPresenter;
import com.yuexun.dhdoctor.module.my.presenter.IMessagePresenter;
import com.yuexun.dhdoctor.module.my.presenter.impl.MessageDetailPresenter;
import com.yuexun.dhdoctor.module.my.presenter.impl.MessagePresenter;
import com.yuexun.dhdoctor.module.my.ui.view.IMessageDetailView;
import com.yuexun.dhdoctor.module.my.ui.view.IMessageView;
import com.yuexun.dhdoctor.module.webview.Act_WebView;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshList;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/4/8 0008.
 */

public class Act_Message extends BaseKJActivity implements IMessageView, IMessageDetailView {

    @Bind(R.id.message_list)
    PullToRefreshList messageList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    @Bind(R.id.edit)
    TextView edit;
    @Bind(R.id.item_icon)
    CheckBox itemIcon;
    @Bind(R.id.delete_view)
    RelativeLayout deleteView;

    private ListView mList;

    IMessagePresenter presenter;
    IMessageDetailPresenter detailPresenter;

    private int nowpage = 1;
    private int pagesize = 99999;
    private boolean isClear = false;

    MessageAdapter adapter;
    ArrayList<MessageInfoBeanDate> messageInfoBeanDates = new ArrayList<>();
    int position;
    boolean isDo;
    BaseEntity baseBean;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_message);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        presenter = new MessagePresenter(new MessageModel(), this);
        detailPresenter = new MessageDetailPresenter(new MessageDetailModel(), this);
        listViewPreference();
        getMessag();

        itemIcon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    for (MessageInfoBeanDate beanDate : messageInfoBeanDates) {
                        beanDate.setSelect(true);
                    }
                } else {
                    for (MessageInfoBeanDate beanDate : messageInfoBeanDates) {
                        beanDate.setSelect(false);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 初始化ListView样式
     */
    private void listViewPreference() {
        mList = messageList.getRefreshView();
        mList.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        mList.setOverscrollFooter(null);
        mList.setOverscrollHeader(null);
        mList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        messageList.setPullLoadEnabled(false);
        ((FooterLoadingLayout) messageList.getFooterLoadingLayout())
                .setNoMoreDataText("已经是最新状态");

        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Act_Message.this.position = position;
                Map<String, String> params = new HashMap<>();
                params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
                params.put("pmIds", messageInfoBeanDates.get(position).getPmId() + "");
                detailPresenter.updateMessageState(params);

            }
        });

        messageList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                messageList.onPullDownRefreshComplete();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                nowpage = 1;
                isClear = true;
                getMessag();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                nowpage++;
                getMessag();
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);

            }
        });
    }

    private void getMessag() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("targetId", "2");
        params.put("pageSize", pagesize + "");
        params.put("pageIndex", nowpage + "");
        presenter.getMessageList(params);
    }

    @OnClick({R.id.back, R.id.edit, R.id.delete_btn, R.id.read_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.edit:
                if (isDo) {
                    adapter.setDo(false);
                    edit.setText("编辑");
                    deleteView.setVisibility(View.GONE);
                } else {
                    adapter.setDo(true);
                    edit.setText("取消");
                    deleteView.setVisibility(View.VISIBLE);
                }
                isDo = !isDo;
                break;
            case R.id.delete_btn:
                List<Integer> pmIds = new ArrayList<>();
                for (MessageInfoBeanDate beanDate : messageInfoBeanDates) {
                    if (beanDate.isSelect()) {
                        pmIds.add(beanDate.getPmId());
                    }
                }
                if (pmIds.size() > 0) {
                    ApiForKjHttp(pmIds);
                } else {
                    ViewInject.toast("请选择要删除的消息");
                }
                break;
            case R.id.read_btn:
                List<Integer> readIds = new ArrayList<>();
                for (MessageInfoBeanDate beanDate : messageInfoBeanDates) {
                    if (beanDate.isSelect()) {
                        readIds.add(beanDate.getPmId());
                    }
                }
                if (readIds.size() > 0) {
                    ApiForRead(readIds);
                } else {
                    ViewInject.toast("请选择要标记的消息");
                }
                break;
        }
    }

    private void ApiForKjHttp(List<Integer> pmIds) {
        String BaseUrl = AppConfig.WEB_SYSTEM + "deletePersonalNotification.json?";
        String partUrl = "";
        for (int i = 0; i < pmIds.size(); i++) {
            partUrl = partUrl + "pmIds=" + pmIds.get(i) + "&";
        }
        if (partUrl != null && partUrl.length() > 0) {
            partUrl = partUrl.substring(0, partUrl.length() - 1);
        }
        BaseUrl = BaseUrl + partUrl;

        KJHttp client = new KJHttp();
        HttpParams params = new HttpParams();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));

        client.post(BaseUrl, params, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                baseBean = JSON.parseObject(t, BaseEntity.class);
                setUi();
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                Toast.makeText(Act_Message.this, "删除失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void ApiForRead(List<Integer> pmIds) {
        String BaseUrl = AppConfig.WEB_SYSTEM + "updateNotificationState.json?";
        String partUrl = "";
        for (int i = 0; i < pmIds.size(); i++) {
            partUrl = partUrl + "pmIds=" + pmIds.get(i) + "&";
        }
        if (partUrl != null && partUrl.length() > 0) {
            partUrl = partUrl.substring(0, partUrl.length() - 1);
        }
        BaseUrl = BaseUrl + partUrl;

        KJHttp client = new KJHttp();
        HttpParams params = new HttpParams();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));

        client.post(BaseUrl, params, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                baseBean = JSON.parseObject(t, BaseEntity.class);
//                setUi();
                if (baseBean.getStatus().equals("200")) {
                    ViewInject.toast("标记成功");
                    isClear = true;
                    getMessag();
                } else {
                    ViewInject.toast("标记失败");
                }
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                Toast.makeText(Act_Message.this, "标记失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setUi() {
        if (baseBean.getStatus().equals("200")) {
            ViewInject.toast("删除成功");
            isClear = true;
            getMessag();
        } else {
            ViewInject.toast("删除失败");
        }
    }

    @Override
    public void showMessage(MessageInfoBean messageInfoBean) {
        if (messageList.isPullRefreshEnabled()) {
            messageList.onPullDownRefreshComplete();
        }
        if (messageInfoBean.getDatas().size() == 0) {
            messageList.setHasMoreData(false);
        } else {
            if (messageList.isPullLoadEnabled()) {
                messageList.onPullUpRefreshComplete();
            }
        }

        if (messageInfoBean.getStatus().equals("200")) {
            if (isClear) {
                if (messageInfoBeanDates.size() > 0) {
                    messageInfoBeanDates.clear();
                }
                isClear = false;
            }

            messageInfoBeanDates.addAll(messageInfoBean.getDatas());
            adapter = new MessageAdapter(mList, messageInfoBeanDates, R.layout.item_message);
            mList.setAdapter(adapter);
            adapter.setDo(isDo);
        } else {
            ViewInject.toast(messageInfoBean.getMessage());
        }

        emptyLayout.dismiss();
    }

    @Override
    public void updateMessageState(BaseEntity baseBean) {
        messageInfoBeanDates.get(position).setState(1);
        adapter.notifyDataSetChanged();
        if (messageInfoBeanDates.get(position).getTypeId() == ActValue.Mail.getNum()) {
            Intent intent = new Intent(Act_Message.this, Act_GetMailList.class);
            startActivity(intent);
        } else if (messageInfoBeanDates.get(position).getTypeId() == ActValue.Notice.getNum()) {
            Intent intent = new Intent(Act_Message.this, Act_WebView.class);
            intent.putExtra("url", AppConfig.WEB_H5 + "notice.html" + "?sessionUuid=" +
                    PreferenceHelper.readString(Act_Message.this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
            startActivity(intent);
        }
    }

}
